package com.lxw.multidb.controller;

import cn.tannn.cat.file.sdk.api.UploadFile;
import cn.tannn.cat.file.sdk.bean.FileIndex;
import cn.tannn.cat.file.sdk.utils.FileUtils;
import cn.tannn.jdevelops.exception.built.BusinessException;
import cn.tannn.jdevelops.result.response.ResultVO;
import com.lxw.multidb.controller.dto.UploadDTO;
import com.lxw.multidb.modules.file.DynFileOperateService;
import com.lxw.multidb.modules.file.TreeNode;
import com.lxw.multidb.modules.file.TreeOptions;
import com.lxw.multidb.modules.file.constants.FileContentType;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;


@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
@Tag(name = "文件管理")
@Slf4j
public class File2Controller {

    private final DynFileOperateService fileOperateService;

    /**
     * 上传文件
     *
     * @param dto 上传参数
     * @return com.sunway.result.response.ResultVO<com.sunway.dymm.controller.file.vo.FileUploadVO>
     * @author lxw
     * @date 2025/6/26 09:56
     **/
    @Operation(summary = "上传文件")
    @PostMapping("/uploadFile")
    public ResultVO<FileIndex> updateFile(@Valid UploadDTO dto) {
        UploadFile uploaded = new UploadFile();
        uploaded.setChildFolder(dto.getPrefix());
        uploaded.setFile(dto.getFile());
        String originalFilename = dto.getFile().getOriginalFilename();
        if (StringUtils.isEmpty(originalFilename)) {
            throw new BusinessException("原始文件损坏，无法获取名称！");
        }
        uploaded.setFileName(originalFilename);
        try {
            FileIndex fileIndex = fileOperateService.upload(uploaded);
            return ResultVO.success(fileIndex);
        } catch (IOException e) {
            log.error("文件上传失败: {}", e.getMessage(), e);
            throw new BusinessException("文件上传失败！");
        }
    }

    @Operation(summary = "懒加载文件列表")
    @GetMapping("/lazyLoadFile")
    @Parameter(name = "fullPath", description = "文件夹路径，根路径传空字符串")
    @Parameter(name = "nameFilter", description = "文件/目录名称过滤关键词")
    public ResultVO<List<TreeNode>> lazyLoadFile(String fullPath, String nameFilter) {
        TreeOptions options = TreeOptions.defaults();
        if (StringUtils.isBlank(fullPath)) {
            fullPath = "";
        }
        if (StringUtils.isNotBlank(nameFilter)) {
            options.setNameFilter(nameFilter);
        }
        List<TreeNode> treeNodes = fileOperateService.loadChildren(fullPath, options);

        return ResultVO.success(treeNodes);
    }

    @GetMapping(value = "/getFileStream")
    @Operation(summary = "获取文件流")
    public ResponseEntity<?> getFileStream(String fileName) {
        log.info("获取文件流: fileName={}", fileName);
        String proPath = FileUtils.proPath(fileName);
        try (InputStream inputStream = fileOperateService.getInputStream(proPath)) {
            byte[] data = inputStream.readAllBytes();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(FileContentType.getContentType(proPath));
            headers.setContentLength(data.length);
            headers.add("Access-Control-Allow-Origin", "*"); // 如需跨域
            return new ResponseEntity<>(data, headers, HttpStatus.OK);
        } catch (Exception e) {
            log.error("获取文件流失败: {}", e.getMessage(), e);
            throw new BusinessException("无法获取文件内容，请检查文件路径或存储配置是否正确。");
        }
    }

}